<template>
  <view class="container">
    <!-- 导航栏 -->
    <view class="navbar">
      <view class="back-btn" @click="navigateBack">返回</view>
      <view class="title">{{ mode === 'edit' ? '修改订单' : '填写订单' }}</view>
      <view class="right-btn"></view>
    </view>

    <!-- 内容区域 -->
    <scroll-view class="scroll-area" scroll-y>
      <view class="bg"></view>
      <view class="page-wapper">
        <!-- 产品信息卡片 -->
        <ProductCard :info="productInfo" />

        <!-- 已选班期 -->
        <view class="cu-list menu">
          <view class="cu-item">
            <view class="content" style="display: flex;justify-content: space-between;">
              <view style="height: 100%;display: flex;justify-content: center;align-items: center;">
                <icon class="iconfont icon-calendar" style="display: flex;align-items: center;" />
                <view style="font-size: 28rpx;color: #303030;font-weight: bold;margin-left: 10rpx;">已选班期</view>
              </view>
              <text style="display: inline-block;padding-left: 30rpx;">
                {{ availableDate?.yearDate + '年' + availableDate?.monthDate + '月' + availableDate?.dayDate + '日'
                }}</text>
            </view>
          </view>
        </view>

        <!-- 卡片容器 -->
        <view class="info-cards">
          <!-- 申请截止时间 -->
          <view class="info-card">
            <view class="card-header">
              <icon class="iconfont icon-calendar"></icon>
              <text class="card-title">申请截止时间</text>
            </view>
            <view class="card-body">
              <text class="label">截止:</text>
              <text class="value" v-if="periodInfo.length > 0">行程出发前 {{ periodInfo[0].periodSku.applicationDeadline }}
                天</text>
            </view>
          </view>

          <!-- 成团确认时间 -->
          <view class="info-card">
            <view class="card-header">
              <icon class="iconfont icon-calendar"></icon>
              <text class="card-title">成团确认时间</text>
            </view>
            <view class="card-body">
              <text class="label">确认:</text>
              <text class="value" v-if="periodInfo.length > 0">行程出发前 {{ periodInfo[0].periodSku.confirmationTime }}
                天</text>
            </view>
          </view>

          <!-- 行程日期/时段 -->
          <view class="info-card">
            <view class="card-header">
              <icon class="iconfont icon-calendar"></icon>
              <text class="card-title">行程日期/时段</text>
            </view>
            <view class="card-body">
              <view class="row">
                <text class="label">出发:</text>
                <text class="value">
                  {{ availableDate?.yearDate + '年' + availableDate?.monthDate + '月' + availableDate?.dayDate + '日' }}
                  {{ availableDate?.startTime }}
                </text>
              </view>
              <view class="row">
                <text class="label">返回:</text>
                <text class="value" v-if="periodInfo.length > 0">
                  出发日起 {{ productInfo.mainInfo.productSku.specificItinerary.length }} 天后 {{ availableDate?.endTime }}
                </text>
              </view>
            </view>
          </view>
        </view>

        <!-- 营员信息 -->
        <view class="cadet-info">
          <view class="section-title">营员信息</view>
          <!-- 营员列表 -->
          <view v-if="cadetList && cadetList.length > 0">
            <view v-for="item in cadetList" :key="item.id" class="block_13" style="padding: 20rpx;height: auto;">
              <view style="height: 100%;align-content: space-between;">
                <view class="group_36">
                  <text lines="1" class="text_34">{{ item.name }}</text>
                  <view class="text-wrapper_13">
                    <text lines="1" class="text_35">{{ item.age }}岁+</text>
                  </view>
                  <text lines="1" class="text_36">儿童</text>
                </view>
                <view class="text_37">身份证号 {{ item.idCard }}</view>
              </view>
              <view class="btn btn_delete"
                style="width: 100rpx;height: 64rpx;border-radius: 8rpx;border: 2rpx solid #fc642f;display: flex;justify-content: center;align-items: center;"
                :data-id="item.id" @tap="delCamper">
                <text style="color: #fc642f;">删除</text>
              </view>
            </view>
            <view style="width: 100%;height: 120rpx;display: flex;justify-content: flex-end;">
              <view @tap="toAddCamper"
                style="display: flex;height: 80rpx;width: 50%;justify-content: center;border: 2rpx solid var(--cyan);border-radius: 8rpx;margin-top: 20rpx;">
                <view style="color: var(--cyan);display: flex;align-items: center;" @tap="GoToAdd">
                  <text class="cuIcon-friendadd"></text>
                  <text class="cuIcon-add"></text>
                  <text class="btn-name">添加参营人员</text>
                </view>
              </view>
            </view>
          </view>
          <view v-else class="empty-cadet" style="text-align: center; padding: 40rpx; color: #999;">
            暂无营员信息，请添加参营人员
            <view
              style="width: 50%;height: 80rpx;display: flex;justify-content: center;border: 2rpx solid var(--cyan);border-radius: 8rpx;margin: 20rpx auto 0 auto;">
              <view style="color: var(--cyan);display: flex;align-items: center;" @tap="GoToAdd">
                <text class="cuIcon-friendadd"></text>
                <text class="cuIcon-add"></text>
                <text class="btn-name">添加参营人员</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 联系信息 -->
        <view class="contact-info">
          <view class="section-title">联系信息</view>
          <view class="input-item">
            <view class="label">联系人</view>
            <input type="text" v-model="contactName" placeholder="请输入联系人姓名" />
          </view>
          <view class="input-item">
            <view class="label">联系电话</view>
            <input type="number" v-model="contactPhone" placeholder="请输入联系电话" />
          </view>
          <view class="input-item">
            <view class="label">电子邮箱</view>
            <input type="email" v-model="contactEmail" placeholder="请输入电子邮箱" />
          </view>
        </view>

        <!-- 发票信息 -->
        <view class="invoice-info">
          <view class="section-title">发票信息</view>
          <view class="invoice-select">
            <text>是否开发票</text>
            <picker mode="selector" range="{{ invoiceOptions }}" bindchange="onInvoiceChange">
              <view class="picker">{{ invoiceOptions[invoiceIndex] }}</view>
            </picker>
          </view>
        </view>

        <!-- 备注信息 -->
        <view class="remark-info">
          <view class="section-title">备注信息</view>
          <textarea v-model="remark" placeholder="请输入备注信息（选填）" rows="3" />
        </view>
      </view>
    </scroll-view>

    <!-- 底部提交按钮 -->
    <view class="bottom-bar">
      <view class="total-price">
        <text>实付金额：</text>
        <text class="price">¥{{ totalPrice || '0.00' }}</text>
      </view>
      <button class="submit-btn" @click="submitOrder">{{ mode === 'edit' ? '更新订单' : '提交订单' }}</button>
    </view>

    <!-- 加载中 -->
    <view class="load-modal" v-if="loadModal">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <text>加载中...</text>
      </view>
    </view>
  </view>
</template>
<script>
import { request } from '@/utils/request.js';
import { mergeAllProducts } from '@/utils/productUtil';
import ProductCard from '@/components/ProductCard.vue';
import Period from '../period/period.vue';

export default {
  components: {
    ProductCard
  },
  data() {
    return {
      // 页面模式：'create' 创建订单，'edit' 修改订单
      mode: 'create',
      orderId: '',
      spuId: '',
      p1sId: '',
      p2sId: '',
      p3sId: '',
      loadModal: true,
      productInfo: null,
      periodInfo: [],
      availableDate: {
        yearDate: new Date().getFullYear(),
        monthDate: new Date().getMonth() + 1,
        dayDate: new Date().getDate()
      },
      contactName: '',
      contactPhone: '',
      contactEmail: '',
      limitData: 0,
      remark: '',
      invoiceOptions: ['不开发票', '开发票'],
      invoiceIndex: 0,
      cadetList: [],
      totalPrice: 0,
      originalOrderData: null // 存储原始订单数据
    };
  },
  onLoad(options) {
    const { spuId, p1sId, p2sId, p3sId, orderId, mode } = options;
    console.log('页面加载参数:', options);

    // 判断页面模式
    if (orderId && mode === 'edit') {
      console.log('进入编辑模式, orderId:', orderId, 'mode:', mode);
      this.mode = 'edit';
      this.orderId = orderId;
    } else {
      console.log('进入创建模式');
      this.mode = 'create';
      this.spuId = spuId;
      this.p1sId = p1sId;
      this.p2sId = p2sId;
      this.p3sId = p3sId;
    }

    //接受子页面发送来的消息
    uni.$on('refreshOrder', () => {
      this.loadData(); // 重新加载参营人员
    });
    this.loadData();
  },
  methods: {
    // 返回上一页
    navigateBack() {
      uni.navigateBack();
    },

    // 加载数据 - 使用请求链方式
    loadData() {
      this.loadModal = true;

      if (this.mode === 'edit') {
        // 编辑模式：先获取订单详情，再加载其他数据
        this.fetchOrderDetail()
          .then(() => this.fetchProductInfomode())
          .then(() => this.fetchPeriodInfo())
          .then(() => {
            // 编辑模式下不需要重新获取营员信息，因为已经从订单中回填了
            // 所有请求完成后计算总金额
            this.calculateTotalPrice();
          })
          .catch(error => {
            console.error('编辑模式加载数据失败:', error);
            uni.showToast({
              title: `加载数据失败: ${error.message || '请重试'}`,
              icon: 'none'
            });
          })
          .finally(() => {
            this.loadModal = false;
          });
      } else {
        // 创建模式：正常加载流程
        this.fetchProductInfo()
          .then(() => this.fetchPeriodInfo())
          .then(() => this.fetchCadetInfo())
          .then(() => {
            // 所有请求完成后计算总金额
            this.calculateTotalPrice();
          })
          .catch(error => {
            console.error('创建模式加载数据失败:', error);
            uni.showToast({
              title: `加载数据失败: ${error.message || '请重试'}`,
              icon: 'none'
            });
          })
          .finally(() => {
            this.loadModal = false;
          });
      }
    },



    // 获取产品信息
    async fetchProductInfo() {
      if (!this.spuId) {
        console.error('spuId为空，无法获取产品信息');
        throw new Error('产品ID不存在');
      }

      console.log('正在获取产品信息，spuId:', this.spuId);

      const productRes = await request({
        url: `/product-spu/getProduct?id=${this.spuId}&merchantType=3`,
        method: 'GET',
        loading: false
      });

      if (productRes.code === 200) {
        this.productInfo = mergeAllProducts([productRes.data], 3)[0];
        console.log('合并后的产品信息:', this.productInfo);
      } else {
        throw new Error('获取产品信息失败');
      }
    },

    // 获取班期信息
    async fetchPeriodInfo() {
      // 如果有班期ID，优先获取真实的班期信息
      if (this.p3sId) {
        console.log('获取班期信息，班期ID:', this.p3sId);

        try {
          const companyRes = await request({
            url: `/period-sku/getMPByIds?ids=${this.p3sId}`,
            method: 'GET',
            loading: false
          });

          if (companyRes.code === 200 && companyRes.data && companyRes.data.length > 0) {
            this.periodInfo = companyRes.data;
            this.availableDate = companyRes.data[0].periodSku.availableDate;
            console.log('获取班期信息成功:', this.periodInfo);
            console.log('班期日期:', this.availableDate);
            return;
          } else {
            console.warn('获取班期信息失败，使用默认信息');
          }
        } catch (error) {
          console.error('获取班期信息出错:', error);
        }
      }

      // 如果没有班期ID或获取失败，使用默认班期信息
      console.log("使用默认班期信息")
      this.periodInfo = [{
        periodSku: {
          availableDate: {
            yearDate: new Date().getFullYear(),
            monthDate: new Date().getMonth() + 1,
            dayDate: new Date().getDate()
          },
          applicationDeadline: 7,
          groupConfirmationTime: 3,
          departureDate: {
            yearDate: new Date().getFullYear(),
            monthDate: new Date().getMonth() + 1,
            dayDate: new Date().getDate() + 7
          },
          returnDate: {
            yearDate: new Date().getFullYear(),
            monthDate: new Date().getMonth() + 1,
            dayDate: new Date().getDate() + 10
          }
        }
      }];
      this.availableDate = this.periodInfo[0].periodSku.availableDate;
      console.log('使用默认班期信息:', this.periodInfo);

      let ids = [];
      if (this.p1sId) {
        ids.push(this.p1sId);
        ids.push(this.p2sId);
        ids.push(this.p3sId);
      } else {
        ids.push(this.p2sId);
        ids.push(this.p3sId);
      }

      const companyRes = await request({
        url: `/period-sku/getMPByIds?ids=${ids}`,
        method: 'GET',
        loading: false
      });

      if (companyRes.code === 200 && companyRes.data && companyRes.data.length > 0) {
        this.periodInfo = companyRes.data;
        console.log('创建模式-班期信息:', companyRes.data);
        this.availableDate = companyRes.data[0].periodSku.availableDate;

        // 确保每个班期项都有正确的periodId
        this.periodInfo.forEach((item, index) => {
          console.log(`班期项${index}的ID字段:`, {
            'item.id': item.id,
            'item.periodId': item.periodId,
            'item.periodSku.id': item.periodSku?.id,
            'p1sId': this.p1sId,
            'p2sId': this.p2sId,
            'p3sId': this.p3sId
          });
        });
      } else {
        throw new Error('获取班期信息失败');
      }
    },

    // 获取营员信息
    async fetchCadetInfo() {
      const cadetRes = await request({
        url: `/campers`,
        method: `GET`,
        loading: false
      });

      if (cadetRes.code === 200) {
        this.cadetList = cadetRes.data;
      } else {
        throw new Error('获取营员信息失败');
      }
    },

    // 计算总金额
    calculateTotalPrice() {
      this.totalPrice = 0;
      this.periodInfo.forEach(item => {
        this.totalPrice += item.periodSku.price;
      });
      this.totalPrice *= (this.cadetList.length);
      console.log('计算的总金额:', this.totalPrice);

    },
    // 提交订单 - 使用request工具发送请求
    async submitOrder() {
      // 表单验证
      if (!this.contactName) {
        return uni.showToast({ title: '请输入联系人姓名', icon: 'none' });
      }
      if (!this.contactPhone || !/^1[3-9]\d{9}$/.test(this.contactPhone)) {
        return uni.showToast({ title: '请输入正确的手机号码', icon: 'none' });
      }
      if (this.contactEmail && !/^\S+@\S+\.\S+$/.test(this.contactEmail)) {
        return uni.showToast({ title: '请输入正确的电子邮箱', icon: 'none' });
      }
      // 检查是否有营员
      if (!this.cadetList || this.cadetList.length === 0) {
        return uni.showToast({ title: '请添加参营人员', icon: 'none' });
      }

      try {

        // 创建订单
        await this.createOrder();


      } catch (error) {
        console.error('操作订单失败:', error);
        uni.showToast({
          title: `${this.mode === 'edit' ? '更新' : '提交'}订单失败，请重试`,
          icon: 'none'
        });
      }
    },

    // 创建订单
    async createOrder() {
      // 构造订单数据
      let data = {
        remark: this.remark,
        name: this.contactName,
        phone: this.contactPhone,
        email: this.contactEmail,
        invoice: this.invoiceIndex === 1,
        invoiceInfo: '',
        items: this.periodInfo.map((item, index) => {
          console.log('创建订单项，item数据:', item);

          // 根据索引和传入的参数确定正确的periodId
          let periodId = '';
          if (index === 0 && this.p1sId) {
            periodId = this.p1sId;
          } else if (index === 1 && this.p2sId) {
            periodId = this.p2sId;
          } else if (index === 2 && this.p3sId) {
            periodId = this.p3sId;
          } else if (this.periodInfo.length === 1 && this.p3sId) {
            // 如果只有一个班期项，使用p3sId
            periodId = this.p3sId;
          } else {
            // 备用方案：尝试从item中获取
            periodId = item.periodSku.id || item.periodId || item.id || '';
          }

          console.log(`订单项${index}使用的periodId:`, periodId);

          return {
            productId: item.periodSku.spuId,
            productName: item.periodSku.name || '',
            price: item.periodSku.price || 0,
            quantity: 1,
            merchantId: item.merchantDTO.id || '',
            skuInfo: '',
            periodId: periodId
          };
        }),
        camperRelations: this.cadetList.map(cadet => ({
          orderId: '',
          camperId: cadet.id
        }))
      };

      // 提交订单 - 使用项目中的request工具
      const res = await request({
        url: '/orders',
        method: 'POST',
        data: data
      });

      if (res.code === 200) {
        uni.showToast({
          title: '提交成功',
          icon: 'success'
        });
        console.log('提交订单成功:', res.data);
        const order = res.data
        // 跳转到我的订单页面
        setTimeout(() => {
          uni.navigateTo({
            url: `/public/order/order`
          });
        }, 1200);


      } else {
        throw new Error(res.message || '提交订单失败');
      }
    },



    // 发票选择变化
    onInvoiceChange(e) {
      this.invoiceIndex = e.detail.value;
    },

    // 删除营员方法
    delCamper(e) {
      const id = e.currentTarget.dataset.id;
      uni.showModal({
        title: '确认删除',
        content: '确定要删除该营员吗？',
        success: (res) => {
          this.deleteCamper(id).then(() => {
            console.log('删除成功');
            this.loadData();
          });
        }
      });
    },
    //删除营员请求
    async deleteCamper(id) {
      const res = await request({
        url: `/campers?id=${id}`,
        method: 'DELETE'
      })
      if (res.code === 200) {
        this.cadetList = this.cadetList.filter(item => item.id !== id);
      } else {
        throw new Error('删除营员信息失败');
      }
    },

    // 添加营员
    GoToAdd() {
      uni.navigateTo({
        url: '/public/period/editPeriod?mode=add'
      });
    },

    // 添加营员（兼容原方法名）
    toAddCamper() {
      this.GoToAdd();
    }
  }
};
</script>

<style scoped>
.container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.navbar {
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.back-btn,
.right-btn {
  width: 80rpx;
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.scroll-area {
  flex: 1;
  overflow-y: auto;
}

.bg {
  width: 100%;
  height: 338rpx;
  position: fixed;
  background: linear-gradient(#fafafa, #f2f2f2);
}

.page-wapper {
  padding-bottom: 300rpx;
  position: relative;
}

.product-info {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.product-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.product-price {
  font-size: 36rpx;
  font-weight: bold;
  color: #f37e22;
}

.cu-list {
  background-color: #fff;
  margin-bottom: 20rpx;
}

.cu-item {
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.cu-bar {
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #eee;
  margin-bottom: 20rpx;
}

.contact-info,
.invoice-info,
.remark-info {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.input-item {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.label {
  width: 150rpx;
  font-size: 28rpx;
  color: #666;
}

input {
  flex: 1;
  height: 80rpx;
  border-bottom: 1rpx solid #eee;
  font-size: 28rpx;
  color: #333;
}

.invoice-select {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.picker {
  color: #999;
  font-size: 28rpx;
}

textarea {
  width: 100%;
  height: 150rpx;
  border: 1rpx solid #eee;
  border-radius: 10rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
  box-sizing: border-box;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 120rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
}

.total-price {
  font-size: 28rpx;
  color: #666;
}

.price {
  font-size: 36rpx;
  font-weight: bold;
  color: #f37e22;
}

.submit-btn {
  width: 250rpx;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #f37e22;
  color: #fff;
  border-radius: 40rpx;
  font-size: 32rpx;
}

.load-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.loading-content {
  background-color: #fff;
  padding: 40rpx;
  border-radius: 10rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  width: 50rpx;
  height: 50rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #f37e22;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

/**卡片 */
.info-cards {
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.info-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
}

.iconfont {
  font-size: 36rpx;
  color: #ff6700;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #303030;
  margin-left: 12rpx;
}


.card-body {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.row {
  display: flex;
  align-items: center;
}

.label {
  font-size: 28rpx;
  font-weight: 500;
  color: #666;
  min-width: 100rpx;
}

.value {
  font-size: 28rpx;
  color: #303030;
  line-height: 1.5;
}


/* 营员信息样式 */
.cadet-info {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 30rpx;
}

.block_13 {
  background-color: #f5f5f5;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;
  position: relative;
}

.group_36 {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.text_34 {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-right: 20rpx;
}

.text-wrapper_13 {
  margin-right: 20rpx;
}

.text_35 {
  font-size: 28rpx;
  color: #f37e22;
  background-color: #fff9f5;
  padding: 5rpx 15rpx;
  border-radius: 4rpx;
}

.text_36 {
  font-size: 28rpx;
  color: #666;
}

.text_37 {
  font-size: 26rpx;
  color: #999;
  margin-top: 10rpx;
}

.btn_delete {
  position: absolute;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
}

.btn-name {
  font-size: 28rpx;
  margin-left: 10rpx;
}

.empty-cadet {
  font-size: 28rpx;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}
</style>